<?php
require_once (APPPATH.'views/components/page.php');
require_once (APPPATH.'models/specialmark_model.php');
require_once (APPPATH.'models/branch_model.php');
require_once (APPPATH.'libraries/stringutils.php');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<link href='<?php echo base_url() ?>resources/css/admin.css' rel='stylesheet' type='text/css' />
		<script src="<?php echo base_url() ?>resources/js/jquery-1.4.2.min.js"></script>
		<script src="<?php echo base_url() ?>resources/js/ckeditor/ckeditor.js"></script>
		<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
		
		<script type="text/javascript">
			function onSaveBtnClicked()
			{
				var ret = true;
				
				// Category
				var categoryName = document.getElementById("productname").value;
				categoryName = categoryName.trim();
				
				if (categoryName.length == 0)
				{
					var nameError = document.getElementById("nameerror");
					nameError.innerHTML = "\t\t\t Vui lòng nhập tên sản phẩm";
					ret = false;
				}
				
				// Image
				var image = document.getElementById("phototxt").value;
				image = categoryName.trim();
				
				if (image.length == 0)
				{
					var imageError = document.getElementById("imageerror");
					imageError.innerHTML = "\t\t\t Vui lòng nhập hình ảnh";
					ret = false;
				}
				
				// Product type
				var productType = document.getElementById("producttypeid");
				var ptid = productType.options[productType.selectedIndex].value;
				
				if (ptid <= 0)
				{
					var productTypeError = document.getElementById("producttypeerror");
					productTypeError.innerHTML = "\t\t\t Vui lòng chọn 1 nhóm sản phẩm";
					ret = false;
				}
				
				// Price
				var priceError = document.getElementById("priceerror");
				var price = document.getElementById("pricetxt").value;
				price = price.trim();
				
				if (price.match(/^[0-9]+$/) == null)
				{
					priceError.innerHTML = "\t\t\t Chỉ nhập số vào giá sản phẩm";
					ret = false;
				}
				
				if (price.length == 0)
				{
					priceError.innerHTML = "\t\t\t Vui lòng nhập giá sản phẩm";
					ret = false;
				}
				
				return ret;
			}
			
			function onCancelBtnClicked(baseurl)
			{
				window.location = baseurl + "product";
			}
			
			function isNumericKey(e)
		    {
		        if (window.event) { var charCode = window.event.keyCode; }
		        else if (e) { var charCode = e.which; }
		        else { return true; }
		        if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
		        return true;
		    }
		</script>
		
		<?php
			$title = isset($product) ? "Cập nhật sản phẩm" : "Thêm sản phẩm";
		?>
		
		<title><?php echo $title ?></title>
	</head>
	
	<body>
		<div id='wrapper'>
			<div id='header'>
				<div id="leftTopPan">
				<a href='<?php echo base_url() ?>'><img src='<?php echo base_url() ?>resources/images/logo.gif' title='Consultant' alt='Consultant' width='160' height='39' border='0' /></a>
				</div>
				<h1></h1>
			</div>
			<div id="middle">
				<div id="container">
					<div id="content">
						<br /><h2 align="center"><?php echo $title ?></h2><br />
						
						<?php
						
						// Error handler
						$error = $this->session->userdata('error');
						$this->session->unset_userdata('error');
						
						if (isset($rerror))
							$error = $rerror;
						
						$errorText = "";
						
						switch ($error) {
							case UPDATE_ERROR:
								$errorText = UPDATE_ERROR_TEXT;
								break;
							case EXISTED_ERROR:
								$name = $this->session->userdata('productname');
								$this->session->unset_userdata('productname');
								$productType = $this->session->userdata('producttypename');
								$this->session->unset_userdata('producttypename');
								$errorText = sprintf(PRODUCT_EXISTED_ERROR_TEXT, "Sản phẩm", $name, $productType);
								break;
							case INSERT_ERROR:
								$error = sprintf(INSERT_ERROR_TEXT, "Sản phẩm");
								break;
							case NOT_EXISTED_ERROR:
								$errorText = NOT_EXISTED_ERROR_TEXT;
								break;
							default:
								break;
						}
						?>
						<h3 style="color: red"><?php echo $errorText ?></h3>
						<?php
						
						
						$userdata = $this->session->userdata('userdata');
						
						if (Page::getInstance()->isAdmin())
						{
							if (isset($product))
							{
								if ($product->getId() < 0)
									return;
							}
							// User information
							Page::getInstance()->generateUserInfo($userdata);
							
							// Begin form
							
							$function = isset($product) ? "processupdate" : "processinsert";
							echo form_open('product/'.$function);
							
							if (isset($product))
							{
								echo form_hidden('productid', $product->getId());
							}
							
							// Text box
							$titleTxt = array(	'id'			=>	'productname',
												'name'			=>	'productname');
												
							// Default values
							$productTypeId = -1;
							$branch = -1;
							$photoUrl = "";
							$priceDefault = "";
							$desc = "";
							$promotion = 0;
							$specialmarks = array();
							
							if (isset($product))
							{ 
								$titleTxt['value'] = StringUtils::getInstance()->decodeHTMLString($product->getName());
								$productTypeId = $product->getProductType()->getId();
								$branch = $product->getBranch()->getId();
								$photoUrl = $product->getImage();
								$priceDefault = $product->getPrice();
								$desc = $product->getDescription();
								$promotion = $product->isPromotion();
								
								foreach ($product->getMarks() as $mark)
								{
									$specialmarks[] = $mark->getId();
								}
							}
						?>
							<p>Tên: 
							<?php echo form_input($titleTxt) ?>
							<label id='nameerror' style='color:red'></label></p>
						<?php
							
							// Product type list
							$categories = Category_Model::getInstance()->getStorageCategories();
							$cateArr = array();
							
							foreach ($categories as $category)
							{
								$productTypeArr = array();
								
								foreach ($category->getProductTypes() as $productType)
								{
									$productTypeArr[$productType->getId()] = "&nbsp;&nbsp;&nbsp;&nbsp;".$productType->getTitle();
								}
								
								if (count($productTypeArr) == 0)
									$productTypeArr[0] = "&nbsp;&nbsp;&nbsp;&nbsp;---- Không có Nhóm sản phẩm ----";
								
								$cateArr[$category->getTitle()] = $productTypeArr;
							}
							
						?>
							<p>Nhóm: 
							<?php echo form_dropdown('producttypeid', $cateArr, $productTypeId, 'id="producttypeid" style="width:300px"') ?>
							<label id="producttypeerror" style="color:red"></label>
							</p>
						<?php
							// Marks
							$marks = SpecialMark_Model::getInstance()->getAllSpecialMarks();
							$markArr = array(0	=> "---- Không chọn ----");
							
							foreach ($marks as $mark)
							{
								$markArr[$mark->getId()] = $mark->getTitle();
							}
						?>
							<p style="vertical-align: top">Nhãn:<br />
								<?php echo form_dropdown('markids[]', $markArr, $specialmarks, 'multiple="multiple" id="markids[]" style="width:300px"') ?> 
							</p>
						<?php
							// Branches
							$branches = Branch_Model::getInstance()->getAllBranches();
							$branchArr = array();
							
							foreach ($branches as $branch)
							{
								$branchArr[$branch->getId()] = $branch->getName();
							}
						?>
							<p>Xuất xứ: <?php echo form_dropdown('branchid', $branchArr, $branch, 'id="branchid" style="width:300px"') ?></p>
						<?php
							
							// Photo
							$photo = array(	'id'	=>	'phototxt',
											'name'	=>	'phototxt',
											'value'	=> 	$photoUrl,
											'size'	=> 	"80");
						?>
							<p>Hình ảnh: 
							<?php echo form_input($photo) ?><label id='imageerror' style='color:red'></label>
							</p>
						<?php
							
							// Price
							$price = array ( 'id'			=>	'pricetxt',
											 'name'			=>	'pricetxt',
											 'value'		=>	$priceDefault,
											 'onkeypress'	=> "return isNumericKey(event)");
							$promotion = array(	'id'	=>	'promotion',
												'name'	=>	'promotion',
												'value'=>	$promotion,
												'checked'=>	$promotion);
						?>
							<p>Giá: 
							<?php echo form_input($price) ?>
							<label id="priceerror" style="color:red"></label>
							</p>
							
							<!--Promotion-->
							<p>Sản phẩm đang khuyến mãi: <?php echo form_checkbox($promotion) ?></p>
						<?php
							
							// Description
						?>
							<p>Mô tả sản phẩm:</p>
							<textarea cols="80" id="description" name="description" rows="20" ><?php echo $desc ?></textarea>
							<script type="text/javascript">
							//<![CDATA[
					
								// Replace the <textarea id="editor"> with an CKEditor
								// instance, using default configurations.
								CKEDITOR.replace( 'description',
									{
										toolbar :
										[
											[ 'Format', 'Font','FontSize', 'Strike', 'Underline', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', 
											'-', 'TextColor', '-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl', 'Image']
										]
									});
					
							//]]>
							</script>
							<?php
							
							echo "<br/>";
							// Save button
							$saveBtn = array(	'id'		=>	'savebtn',
												'name'		=> 	'savebtn',
												'value'		=>	'Lưu',
												'onclick'	=>	'return onSaveBtnClicked()');
							echo form_submit($saveBtn);
							
							// Reset button
							$cancelBtn = array(	'id'		=> 'cancelbtn',
												'name'		=> 'cancelbtn',
												'value'		=> 'Hủy',
												'onclick'	=> "onCancelBtnClicked('".base_url()."')");
							echo form_reset($cancelBtn);
							
							// End insert form
							echo form_close();
						}
						?>
					</div>
				</div>
					<?php
						if (Page::getInstance()->isAdmin())
						{
							Page::getInstance()->generateAdminLeftMenu();
						}
					?>
			</div>
		</div>
		
	</body>
</html>